package cn.myweb.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.components.Param;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileUploadAction extends ActionSupport {

    private File upload;//文件对象
    private String uploadContentType; //文件类型
    private String uploadFileName;//文件名称
    private String savaPath; //保存路径

    @Action(value = "upload"
            ,params = {"savaPath","/upload"}
            ,results = {
            @Result(name = "input",location = "upload.jsp")
            ,@Result(name = "success",location = "success.jsp")
    })
    public String upload() throws Exception {
        System.out.println("---------fileUpload");
        byte[] buffer =new byte[1024];
        //读取的文件流
        FileInputStream fis = new FileInputStream(getUpload());
        //保存并设置路径
        FileOutputStream fos = new FileOutputStream(getSavaPath()+"\\"
                                +this.getUploadFileName());

        //读取并写入
        int length = fis.read();
        while (length>0){
            fos.write(buffer,0,length);
            length = fis.read(buffer);
        }
        fis.close();
        fos.flush();
        fis.close();
        return "success";
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getSavaPath() {
       // return savaPath;
        String server_path =ServletActionContext.getRequest().getRealPath(File.separator); //ServletActionContext.getServletContext().getRealPath(savaPath);
        int endIndex = server_path.lastIndexOf("\\");
        String path =server_path.substring(0,endIndex)+File.separator+"upload";
        System.out.println("path: " +path);
        return path;
    }

    public void setSavaPath(String savaPath) {
        this.savaPath = savaPath;
    }
}
